package com.example.bangbangxia.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.bangbangxia.dao.UserMapper;
import com.example.bangbangxia.domain.User;
import com.example.bangbangxia.service.UserService;
import com.example.bangbangxia.utils.JwtUtils;
import com.example.bangbangxia.utils.RedisUtils;
import com.example.bangbangxia.utils.RespBean;
import org.apache.juli.logging.Log;
import org.apache.juli.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

@Service
public class UserServiceImpl implements UserService {

    private Log log = LogFactory.getLog(UserService.class);

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private RedisUtils redisUtils;

    /**
     * 添加用户
     * @param user
     * @return
     */
    @Override
    public int insertUser(User user) {
        return userMapper.insert(user);
    }

    /**
     * 查询所有用户
     * @param currentPage
     * @param pageSize
     * @return
     */
    @Override
    public RespBean getUserByPage(Integer currentPage, Integer pageSize) {
        //分页插件
        Page<User> page = new Page<>(currentPage, pageSize);
        userMapper.selectPage(page, null);
        List<User> list=page.getRecords();
        return RespBean.ok(page);
    }

    /**
     * 更新用户
     * @param user
     * @return
     */
    @Override
    public RespBean updateUser(User user) {
        if (userMapper.updateById(user) ==1){
            return RespBean.ok(user);
        }
        return RespBean.error("更新个人信息出错");
    }

    /**
     * 删除用户
     * @param
     * @return
     */
    @Override
    public int deleteUserById(Integer userId) {
        return userMapper.deleteById(userId);
    }

    /**
     * 修改用户密码
     * @param user
     * @return
     */
    @Override
    public int updateUserPassword(User user) {
        return userMapper.updateById(user);
    }

    /**
     * 根据id查询用户信息
     * @param
     * @return
     */
    @Override
    public User findUserById(int userId) {
        return userMapper.selectById(userId);
    }

    /**
     * 根据姓名查找用户
     * @param userPhone
     * @return
     */
    public User findUserByPhone(String userPhone) {
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("user_phone", userPhone);
        return userMapper.selectOne(wrapper);
    }

    /**
     * 登录
     * @param userPhone
     * @param userPassword
     * @return
     */
    @Override
    public RespBean login(String userPhone, String userPassword) {
        if (userPhone == null || userPhone == ""){
            log.error("登录用户名为空");
            return RespBean.error("登录用户名不能为空");
        }else {
            User user = findUserByPhone(userPhone);
            if (user != null && user.getUserPassword().equals(userPassword)){
                log.info("登录成功");
                Map<String,Object> map = new HashMap<String, Object>();
                JwtUtils jwtUtils = new JwtUtils();
                map.put("user",user);
                map.put("loginToken",jwtUtils.getToken(user));
                return RespBean.ok(map);
            }
            log.error("登录失败，用户名或密码错误");
            return RespBean.error("账号或密码不正确！");

        }
    }

    /**
     * 注册
     * @param userPhone
     * @param userPassword
     * @param userPassword2
     * @return
     */
    @Override
    public RespBean register(String userPhone, String userPassword, String userPassword2) {
        if (userPhone == null || userPhone == ""){
            log.error("注册手机号为空");          //提示信息
            return RespBean.error("手机号不能为空"); //返回错误信息
        }else if (userPassword == null || userPassword == ""){
            log.error("注册密码为空");
            return RespBean.error("密码不能为空");
        } else if (userPassword.length() < 6){
            log.error("您的密码长度小于6个字符");
            return RespBean.error("密码长度小于6个字符");
        }else if (!(userPassword.equals(userPassword2))){
            log.error("两次密码不匹配");
            return RespBean.error("两次输入的密码不匹配");
        }else {
            User user = findUserByPhone(userPhone);
            if (user != null){
                log.error("该手机已被注册：" + userPhone);
                return RespBean.error("此手机号已被注册，注册失败");
            }else {
                user = new User();
                user.setUserName(userPhone);
                user.setUserPassword(userPassword);
                int id = userMapper.insert(user);
                user.setUserId(id);
                log.info("注册成功" + userPhone);
                Map<String,Object> map = new HashMap<String,Object>();
                JwtUtils jwtUtils = new JwtUtils();
                map.put("user",user);
                map.put("loginToken",jwtUtils.getToken(user));
                return RespBean.ok(map);
            }
        }
    }

    /**
     * 发送验证码
     * @param userPhone
     * @return
     */
    public RespBean loginByPhone(String userPhone) {
        //1.生成code和key
        String code = "";
        Random random = new Random();
        for (int i = 0; i < 5; i++) {
            int rand=random.nextInt(10);
            code+=rand;
        }
        String codeKey="userPhone:"+userPhone+",code:"+code;
        log.info("验证码key为："+codeKey);
        log.info("验证码为"+code);
        //2.存入redis中
        redisUtils.set(codeKey, code);
        redisUtils.expire(codeKey, 60);//设置过期时间为60秒
        //3.发送信息（已经成功实现，1条5分钱，所以注释掉）
//        if (SendSmsUtils.send(userPhone, code)!=1) {
//            return RespBean.error("出错了，请重新发送");
//        }
        return RespBean.ok("请输入验证码");
    }

    /**
     * 验证验证码是否正确
     * @param userPhone
     * @param code
     * @return
     */
    @Override
    public RespBean loginByPhoneCheck(String userPhone, String code) {
        //1.拼接codeKey
        String codeKey="userPhone:"+userPhone+",code:"+code;
        //2.查询redis中value
        String codeOld= (String) redisUtils.get(codeKey);
        if (codeOld!=null&&code.equals(codeOld)){
            //验证成功，可以登陆
            log.info("手机号为:"+userPhone+"登陆成功");

            //判断用户是否注册过，没注册过存入数据库，有则取出数据返回
            User user = findUserByPhone(userPhone);//根据手机号查询用户
            if (user==null){
                user=new User();
                user.setUserPhone(userPhone);
                user.setUserPassword("123456");
                userMapper.insert(user);//存入数据库
            }
            user=findUserByPhone(userPhone);//重新取出,为了取到自动生成的id
            //生成token
            Map<String,Object> map = new HashMap<String, Object>();
            JwtUtils jwtUtils = new JwtUtils();
            map.put("user",user);
            map.put("loginToken",jwtUtils.getToken(user));
            return RespBean.ok("登陆成功,默认密码:123456,请尽快修改密码", map);
        }
        return RespBean.error("验证失败，请重新验证");
    }

}
